#! /bin/bash

set -euE

# Add a file-mover.sh script for moving deb packages from /opt/share directory to /var/www/html
cat <<'EOF' > $target/usr/bin/file-mover.sh
#!/usr/bin/env bash

basedir=/opt/share
outdir=/var/www/html

rm -rf $basedir/*

inotifywait -m /opt/share -e create -e moved_to |
    while read -r directory action file; do
        if [[ -f "$basedir/$file" ]] && [[ "$file" == *.deb ]] && dpkg -I "$basedir/$file"; then
            mv $basedir/$file $outdir
        else
            rm -rf $basedir/$file
        fi
    done

EOF

chmod +x $target/usr/bin/file-mover.sh

# Run the file-mover.sh script as a systemd service
cat <<'EOF' > $target/etc/systemd/system/file-mover.service
[Unit]
Description=file mover
After=network.target

[Service]
ExecStart=/usr/bin/file-mover.sh
Restart=always

[Install]
WantedBy=multi-user.target
EOF

ln -s /etc/systemd/system/file-mover.service $target/etc/systemd/system/multi-user.target.wants/file-mover.service

rm -rf $target/var/www/html/*
